package com.taptech.doufu.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.TextView;

import com.taptech.doufu.R;

import androidx.core.content.ContextCompat;

/**
 * 辅助类,判断字符串是否为空
 * 
 * @author Joe Chan
 * @date 2012-10-16
 */

public class TextUtil {
	/**
	 * 判断字符串是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (null == str || str.equals("")) {
			return true;
		} else {
			return false;
		}
	}

	public static void copyString2Clipboard(Context context , String string){
		ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		ClipData data = ClipData.newPlainText("label" , string);
		clipboard.setPrimaryClip(data);
	}

	/**
	 * 设置TextView段落间距
	 *
	 * @param context          上下文
	 * @param tv               给谁设置段距，就传谁
	 * @param content          文字内容
	 * @param paragraphSpacing 请输入段落间距（单位dp）
	 * @param lineSpacingExtra xml中设置的的行距（单位dp）
	 */
	public static void setParagraphSpacing(Context context, TextView tv, String content, int paragraphSpacing, int lineSpacingExtra) {
		if (!content.contains("\n")) {
			tv.setText(content);
			return;
		}
		content = content.replace("\n", "\n\r");

		int previousIndex = content.indexOf("\n\r");
		//记录每个段落开始的index，第一段没有，从第二段开始
		List<Integer> nextParagraphBeginIndexes = new ArrayList<>();
		nextParagraphBeginIndexes.add(previousIndex);
		while (previousIndex != -1) {
			int nextIndex = content.indexOf("\n\r", previousIndex + 2);
			previousIndex = nextIndex;
			if (previousIndex != -1) {
				nextParagraphBeginIndexes.add(previousIndex);
			}
		}
		//获取行高（包含文字高度和行距）
		float lineHeight = tv.getLineHeight();

		//把\r替换成透明长方形（宽:1px，高：字高+段距）
		SpannableString spanString = new SpannableString(content);
		Drawable d = ContextCompat.getDrawable(context, R.drawable.paragraph_space);
		float density = context.getResources().getDisplayMetrics().density;
		//int强转部分为：行高 - 行距 + 段距
		d.setBounds(0, 0, 1, (int) ((lineHeight - lineSpacingExtra * density) / 1.2 + (paragraphSpacing - lineSpacingExtra) * density));

		for (int index : nextParagraphBeginIndexes) {
			// \r在String中占一个index
			spanString.setSpan(new ImageSpan(d), index + 1, index + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		tv.setText(spanString);
	}


	/**
	 * 分割返回结果
	 * 
	 * @param response
	 *            返回字符串
	 * @return
	 */
	public static Map<String, String> splitResponse(String response)
			throws Exception {
		// 保存返回结果
		Map<String, String> map = new HashMap<String, String>();
		// 判断是否为空
		if (!TextUtil.isEmpty(response)) {
			// 已“&”进行分割
			String[] array = response.split("&");
			if (array.length > 2) {
				String tokenStr = array[0]; // oauth_token=xxxxx
				String secretStr = array[1];// oauth_token_secret=xxxxxxx
				String[] token = tokenStr.split("=");
				if (token.length == 2) {
					map.put("oauth_token", token[1]);
				}
				String[] secret = secretStr.split("=");
				if (secret.length == 2) {
					map.put("oauth_token_secret", secret[1]);
				}
			} else {
				throw new Exception("分割字符串不符合要求。");
			}
		} else {
			throw new Exception("分割字符串为空");
		}
		return map;
	}

	/**
	 * 参数反编码
	 * 
	 * @param s
	 * @return
	 */
	public static String decode(String s) {
		if (s == null) {
			return "";
		}
		try {
			return URLDecoder.decode(s, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	public static void handleTextView(TextView textView, CharSequence textStr, int maxLine) {
		textView.setText(textStr);// 首先要赋值一次，让系统自动处理，产生自动换行
		ViewTreeObserver vto = textView.getViewTreeObserver();
		MyOnGlobalLayoutListener layoutListener = new MyOnGlobalLayoutListener(
				textView, textStr,maxLine);
		vto.addOnGlobalLayoutListener(layoutListener);
	}
	static public String subString(String des, int subLong){
		String content = "";
		if (des != null) {
			if (des.length() < subLong) {
				content = des;
			} else {
				content = des.substring(0, subLong - 1) + "...";
			}
		}
		return content;
	}

	static public void setText(TextView textview , String str){
		if (textview != null && str != null){
			textview.setText(str);
		}
	}

}

class MyOnGlobalLayoutListener implements OnGlobalLayoutListener {
	private TextView textView;
	private CharSequence textValue;
	private int maxLine;

	public MyOnGlobalLayoutListener(TextView textView, CharSequence textValue, int maxLine) {
		this.textView = textView;
		this.textValue = textValue;
		this.maxLine = maxLine;
	}

	@Override
	public void onGlobalLayout() {
		ViewTreeObserver obs = textView.getViewTreeObserver();
		obs.removeGlobalOnLayoutListener(this);
		if (textView.getLineCount() > maxLine) {
			int lineEndIndex = this.textView.getLayout().getLineEnd(maxLine-1);// 获取被截断的字符长度
			if (textValue.length() > lineEndIndex) {
				String text = textValue.subSequence(0, lineEndIndex - (maxLine-1))
						+ "...";// 手动加上省略号
				textView.setText(text);
			}
		}
	}
}
